<?php
include_once(APP.'/Config/navigation.php');

class NavigationComponent extends Component {
	function getTree($permissions = array()){
		//Wrap permissions parameter in array
		if(!is_array($permissions)) $permissions = array($permissions);

		return $this->_cleanSubtree($permissions, Configure::read('Navigation.tree'));
	}

	private function _cleanSubtree($userPermission, $subTree){
		$filteredTree = $subTree;
		foreach($subTree as $index=>$link){
			//Check if permissions are set
			if(isset($link['permission'])){
				//Wrap link permissions in an array
				if(!is_array($link['permission']))
					$link['permission'] = array($link['permission']);

				//check for matching permission
				if(!array_count_values(array_intersect($link['permission'], $userPermission))){
					unset($filteredTree[$index]);
					continue;
				}
			}

			//Recurse through subtrees
			if(isset($link['children']) && is_array($link['children'])){
				$filteredTree[$index]['children'] = $this->_cleanSubtree($userPermission, $link['children']);
			}
		}
		return $filteredTree;
	}

}

